package org.example.netty.decode;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.List;

/**
 * 计算两两数据的和
 */
public class IntegerAddDecoder extends ReplayingDecoder<IntegerAddDecoder.STATE_PHASE> {

    enum STATE_PHASE {
        PHASE_1,
        PHASE_2
    }

    private int first;

    private int second;

    public IntegerAddDecoder() {
        // 默认处于第一阶段
        checkpoint(STATE_PHASE.PHASE_1);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        switch (state()) {
            case PHASE_1:
                int i = in.readInt();
                first = i;
                checkpoint(STATE_PHASE.PHASE_2);
                break;
            case PHASE_2:
                int j = in.readInt();
                second = j;
                out.add(first+second);
                checkpoint(STATE_PHASE.PHASE_1);
                break;
            default:
                break;
        }
    }
}
